package com.longteng.java.web.dblesson.dao.impl;

import com.longteng.java.web.dblesson.dao.TbUserDao;
import com.longteng.java.web.dblesson.entity.TbUserEntity;
import com.longteng.java.web.dblesson.mapper.TbUserMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by tianqing.wang
 * DATE : 2018/4/15
 * TIME : 下午3:09
 * PROJECT : web-lesson
 * PACKAGE : com.longteng.java.web.dblesson.dao.impl
 *
 * @author <a href="mailto:celeskyking@163.com">tianqing.wang</a>
 */
@Repository
public class TbUserDaoImpl implements TbUserDao{

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private TbUserMapper tbUserMapper;


    @Override
    public TbUserEntity selectById(Integer id) {
        List<TbUserEntity> userEntities = jdbcTemplate.query("select * from tb_user where id = ?", tbUserMapper,id);
        if(userEntities.isEmpty()){
            return null;
        }else if (userEntities.size() == 1){
            return userEntities.get(0);
        }else{
            throw new RuntimeException("不可能");
        }
    }

    @Override
    public void update(TbUserEntity userEntity) {
        jdbcTemplate.update("update tb_user set username = ?, " +
                "team = ?,  " +
                "age = ?, "+
                "company = ?, "+
                "leader = ? WHERE id = ?",userEntity.getUserName(),
                userEntity.getTeam(),
                userEntity.getAge(),
                userEntity.getCompany(),
                userEntity.getLeader(),
                userEntity.getId());
    }

    @Override
    public void delete(Integer id) {
        jdbcTemplate.update("delete from tb_user where id = ?",id);
    }

    @Override
    public List<TbUserEntity> selectByLeader(String leaderName) {
        return jdbcTemplate.query("select * from tb_user where leader = ?", tbUserMapper,leaderName);
    }

    @Override
    public void insert(TbUserEntity tbUserEntity) {
        jdbcTemplate.update("insert into tb_user(`username`,`team`,`age`,`company`,`leader`) VALUES(?,?,?,?,?)",
                tbUserEntity.getUserName(),
                tbUserEntity.getTeam(),
                tbUserEntity.getAge(),
                tbUserEntity.getCompany(),
                tbUserEntity.getLeader());
    }
}
